package com.dy.course.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dy.course.common.BaseException;
import com.dy.course.common.BaseService;
import com.dy.course.common.Constant;
import com.dy.course.entity.MeetingBean;
import com.dy.course.entity.MeetingCreate;
import com.dy.course.entity.MeetingSignInfo;
import com.dy.course.entity.MeetingUserSeat;
import com.dy.course.enumerate.MeetingStatus;
import com.dy.course.mapper.MeetingMapper;
import com.dy.course.mapper.MeetingSignMapper;
import com.dy.course.mapper.MeetingUserMapper;
import com.dy.course.model.Meeting;
import com.dy.course.model.MeetingSign;
import com.dy.course.model.MeetingUser;
import com.dy.course.service.IMeetingService;
import com.dy.course.util.DateUtil;

import tk.mybatis.mapper.entity.Example;

@Service
public class MeetingService extends BaseService<Meeting> implements IMeetingService {

	@Autowired
	private MeetingMapper meetingMapper;

	@Autowired
	private MeetingSignMapper meetingSignMapper;

	@Autowired
	private MeetingUserMapper meetingUserMapper;

	

	@Transactional
	@Override
	public void meetingCreate(MeetingCreate mc) {
		/*
		 * @@@ 数据验证,业务验证
		 * 
		 */
		logger.info("【创建会议服务】参数信息:" + JSON.toJSONString(mc));
		Meeting meeting = new Meeting();
		BeanUtils.copyProperties(mc, meeting);
		logger.info("插入会议信息,参数信息:" + JSON.toJSONString(meeting));
		meeting.setPictureId(Constant.DEFAULT_COURSE_PIC_ID);
		meeting.setStatus(MeetingStatus.NEW.getCode().byteValue());
		meeting.setCreateTime(DateUtil.now());
		getMapper().insertSelective(meeting);

		List<MeetingUserSeat> list = mc.getUserSeatList();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("list", list);
		params.put("meetingId", meeting.getId());
		logger.info("插入会议信息,参数信息:" + JSON.toJSONString(params));
		meetingMapper.insertMeetingUser(params);
	}


	@Override
	public void sign(MeetingSignInfo msi) {
		String jsonStr = JSON.toJSONString(msi);
		logger.info("【会议签到服务】,参数信息:msi=" + jsonStr);
		// 查看会议是否可以签到
		Meeting meeting = meetingMapper.selectByPrimaryKey(msi.getMeetingId());
		if (meeting == null) {
			logger.error("数据已经被删除或者不存在" + JSON.toJSONString(meeting));
			throw new BaseException(Constant.Code.SELECT_ERROR, "数据已经被删除或者不存在", null);
		}
		
		
		//mck会议id重复不可以签到
		Example example = new Example(MeetingSign.class);
		example.createCriteria().andCondition("meeting_id="+msi.getMeetingId()+" and mck='"+msi.getMck()+"'");
		List<MeetingSign> list = meetingSignMapper.selectByExample(example);
		if(list.size()>=1){
			if(list.get(0).getUserId() == msi.getUserId()){
				throw new BaseException(Constant.Code.ALREADY_SIGN, "已经签到", null);
			}else{
			logger.error("会议mck重复不可签到:list="+JSON.toJSONString(list)+",msi="+list.get(0));
			throw new BaseException(Constant.Code.MCK_ALREADY_SIGN, "不可重复签到", null);
			}
		}
		
		
		//已经签到不可重复签到
		example.clear();
		example.createCriteria().andCondition("meeting_id="+msi.getMeetingId()+" and user_id='"+msi.getUserId()+"'");
		List<MeetingSign> listId = meetingSignMapper.selectByExample(example);
		if(listId.size()>=1){
				throw new BaseException(Constant.Code.ALREADY_SIGN, "已经签到", null);
		}
		
		
		// 没有加入到课程的不能签到
		MeetingUser meetingUserQuery = new MeetingUser();
		BeanUtils.copyProperties(msi, meetingUserQuery);
		int isJoin = meetingUserMapper.selectCount(meetingUserQuery);
		if (isJoin == 0) {
			logger.error("没有参加会议的不能签到");
			throw new BaseException(Constant.Code.NOT_JOIN, "没有参加会议的不能签到", null);
		}

		// 已经签到的不能再进行签到
		MeetingSign meetingSignQuery = new MeetingSign();
		BeanUtils.copyProperties(msi, meetingSignQuery);
		int isSign = meetingSignMapper.selectCount(meetingSignQuery);
		if (isSign > 0) {
			logger.error("已经签到");
			throw new BaseException(Constant.Code.ALREADY_SIGN, "已经签到", null);
		}
		
		// 插入签到信息
		MeetingSign insertMeetingSign = new MeetingSign();
		BeanUtils.copyProperties(msi, insertMeetingSign);
		insertMeetingSign.setTime(new Date());
		//insertMeetingSign.setStatus(SignStatus.SIGNED.getCode().byteValue());
		logger.info("【会议签到服务】,参数信息:msi=" + insertMeetingSign);
		int count = meetingSignMapper.insert(insertMeetingSign);
		if (count < 1) {
			logger.error("数据库异常");
			throw new BaseException(Constant.Code.INSERT_ERROR, "数据库插入异常", null);
		}

	}

	@Override
	public List<MeetingBean> selectMeeting(MeetingBean mb) {
		logger.info("【创建者会议列表信息】,参数信息:mb=" + JSON.toJSONString(mb));
		super.startPage(mb);
		return meetingMapper.selectMeeting(mb);
	}


	@Override
	public List<MeetingBean> selectMeetingForUser(MeetingBean mb) {
		logger.info("【参与者会议列表信息】,参数信息:mb=" + JSON.toJSONString(mb));
		super.startPage(mb);
		return meetingMapper.selectMeetingForUser(mb);
	}

	/**
	 * 删除会议
	 */
	@Override
	public void deletMeeting(MeetingBean mb) {
		logger.info("【删除会议】,参数信息:mb=" + JSON.toJSONString(mb));
		Meeting m =meetingMapper.selectByPrimaryKey(mb.getId());
		if(m == null){
			logger.error("【】数据库异常,数据已经被删除或者不存在,courseDetailId={}",mb.getId());
			throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据被删除或者不存在", null);
		}
		int count = meetingMapper.deleteByPrimaryKey(mb.getId());
		if(count < 1){
			logger.error("【】数据库异常,数据已经被删除或者不存在,courseDetailId={}",mb.getId());
			throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据被删除或者不存在", null);
		}
		
		//删除会议用户信息
		Example example = new Example(MeetingUser.class);
		example.createCriteria().andEqualTo("meetingId",mb.getId());
		meetingUserMapper.deleteByExample(example);
		
		//删除签到会议信息
		example = new Example(MeetingSign.class);
		example.createCriteria().andEqualTo("meetingId",mb.getId());
		meetingSignMapper.deleteByExample(example);
	}

	
	//修改会议(暂时不用，留作后用)
	@Override
	public void updateMetting(MeetingBean mb) {
		logger.info("【修改会议】,参数信息:mb=" + JSON.toJSONString(mb));
		Meeting m =meetingMapper.selectByPrimaryKey(mb.getId());
		if(m == null){
			logger.error("【】数据库异常,数据已经被删除或者不存在,courseDetailId={}",mb.getId());
			throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据被删除或者不存在", null);
		}
		BeanUtils.copyProperties(mb, m);
		int count = meetingMapper.updateByPrimaryKey(m);
		if(count < 1){
			logger.error("【】数据库异常,数据修改失败,mb=",JSON.toJSONString(mb));
			throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据修改失败", null);
		}
		List<MeetingUser> meetingUsers = mb.getMeetingUsers();
		Example example = new Example(MeetingUser.class);
		for (MeetingUser meetingUser : meetingUsers) {
			logger.info("【会议用户操作】,参数信息:meetingUser=" + JSON.toJSONString(meetingUser));
			example.clear();
			//meetingUser.getType()==1删除
			if(meetingUser.getType() == 1){
				example.createCriteria().andEqualTo("userId",meetingUser.getUserId()).andEqualTo("meetingId",mb.getId());
				count = meetingUserMapper.selectCountByExample(example);
				if(count < 1){
					logger.error("【】数据库异常,数据已经被删除或者不存在,meetingUser=",JSON.toJSONString(meetingUser));
					throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据已经被删除或者不存在", null);
				}
				example.createCriteria().andEqualTo("userId",meetingUser.getUserId()).andEqualTo("meetingId",mb.getId());
				meetingUserMapper.deleteByExample(example);
			}
			//meetingUser.getType()==2增加
			if(meetingUser.getType() == 2){
				example.createCriteria().andEqualTo("userId",meetingUser.getUserId()).andEqualTo("meetingId",mb.getId());
				count = meetingUserMapper.selectCountByExample(example);
				if(count > 0){
					logger.error("【】数据库异常,数据已存在,meetingUser=",JSON.toJSONString(meetingUser));
					throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据已存在", null);
				}
				meetingUser.setMeetingId(mb.getId());
				meetingUserMapper.insert(meetingUser);
			}
			//meetingUser.getType()==3修改（不能修改人，只能修改座位）
			if(meetingUser.getType() == 3){
				example.createCriteria().andEqualTo("userId",meetingUser.getUserId()).andEqualTo("meetingId",mb.getId());
				count = meetingUserMapper.selectCountByExample(example);
				if(count < 1){
					logger.error("【】数据库异常,数据已经被删除或者不存在,meetingUser=",JSON.toJSONString(meetingUser));
					throw new BaseException(Constant.Code.DELETE_ERROR, "数据库异常,数据已经被删除或者不存在", null);
				}
				example.createCriteria().andEqualTo("userId",meetingUser.getUserId()).andEqualTo("meetingId",mb.getId());
				meetingUserMapper.updateByExampleSelective(meetingUser, example);
			}
		}
	}

	/**
	 * 查询学生签到信息
	 */
	@Override
	public List<MeetingUserSeat> selectSignUser(MeetingUserSeat mus) {
		logger.info("【查询学生签到信息】,参数信息:mus=" + JSON.toJSONString(mus));
		List<MeetingUserSeat> list = meetingSignMapper.selectSignUser(mus);
		if(list.size() < 1){
			logger.error("【】数据库异常,无法查询数据,meetingUser=",JSON.toJSONString(mus));
			throw new BaseException(Constant.Code.SELECT_ERROR, "数据库异常,数据已经被删除或者不存在", null);
		}
		return list;
	}
}
